import axios from "axios";
import { useUserStoreHook } from "@/store/modules/user";
import {useAppStoreHook} from "@/store/modules/app.js";

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50 * 1000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStoreHook();
    const appStore = useAppStoreHook();
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    //后端请求优先级配置项
    config.headers['Priority-Value'] = appStore.groupName
    return config;
  },
  (error) => {
    console.warn(error, 'requestInterceptorError') // for debug
    return Promise.reject(error)
  }
);

// 响应拦截器 后端响应状态码和浏览器状态码保持一致
service.interceptors.response.use(
    //浏览器状态码成功
(response) => {
    const { data, status, headers} = response
    // 下载文件
    if (headers["content-disposition"]) return response
    // 业务逻辑错误
    if (status === 200){
      if (data && data.code !== 200){
        ElMessage.error({
          message: data.code + ' ' + data.msg,
          duration: 5 * 1000
        })
      }else if(!data) {
        ElMessage.error({
          message: 'Error Connect Refused',
          duration: 5 * 1000
        })
      }
    }
    return data
  },
  (error) => {
    //浏览器状态码失败
    const { status, statusText, data } = error.response
    if (status === 401) {
      // 重新登录
      ElMessageBox.confirm("当前登录信息过期,请重新登录", "提示", {
        confirmButtonText: "确定",
        type: "warning",
      }).then(() => {
        useUserStoreHook().resetStore()
        window.location.href = "/";
      })
      return
    }
    if (status) {
      ElMessage.error({
        message: status + ' ' + (data.msg || statusText),
        duration: 5 * 1000
      })
      return error.response
    }
    console.warn(error.response, 'responseInterceptorError') // for debug
    return Promise.reject(error)
  }
);

// 导出 axios 实例
export default service;
